var curUrl = window.location.host;
var baseUrl = 'http://'+curUrl;
var suggestionUrl = baseUrl + '/map/suggest?query=';
var mapUrl = baseUrl + "/map/count";
var roomUrl = baseUrl + "/map/list";
//通勤接口
var configUrl = baseUrl + "/map/config";
var tqMapUrl = baseUrl + "/map/count";
var tqRoomUrl = baseUrl + "/map/list";

var RZCONFIG = {
    cityName: '重庆',
    lng: 106.555562,
    lat: 29.567739
};

$('#mapBox').append('<p id="tips">本页面通勤时间来源于百度地图</p>');

var rzroomMap = {};

var J_Mykeywords = $('#J_MyKeywords'),
    J_keywords = $('#J_keywords'),
    aSelectList = $('.selectList'),
    oScrollContent = $('#scrollContent'),
    J_bgShadow = $('#J_bgShadow') //透明背景
    ,
    J_selectListForA = $('.J_selectListForA') //一般单选项
    ,
    J_typeNum = $('#J_typeNum') //居室类别计数
    ,
    J_moreNum = $('#J_moreNum') //更多的计数
    ,
    J_areaListBox = $('#J_areaListBox') //面积的div
    ,
    J_priceVal = $('#J_priceVal'),
    J_faceVal = $('#J_faceVal'),
    J_areaVal = $('#J_areaVal'),
    J_typeVal = $('#J_typeVal'),
    J_QfaceList = $('#J_faceList'),
    J_QpriceList = $('#J_priceList'),
    J_QareaList = $('#J_areaList'),
    J_QtypeList = $('#J_typeList'),
    J_roundName = $('#J_roundName'),
    J_round = $('#J_round'),
    J_roundList = $('#J_roundList'),
    J_tqType = $('#J_tqType'),
    J_tqMin = $('#J_tqMin'),
    J_sortingList = $('#J_sortingList'),
    J_houseList = $('#J_houseList'),
    J_loading = $('#J_loading'),
    J_noneHouse = $('#J_noneHouse'),
    J_centerTqMarker = $('#J_centerTqMarker'),
    J_tips = $('#tips'),
    J_clear = $('#J_clear'),
    J_TqBox = $('#J_TqBox'),
    J_mainLoading = $('#J_mainLoading'),
    myKeywordFlag = false,
    ajaxFlag = true,
    centerPoint = '',
    tqFlag = false,
    tqData = null,
    tqDragFlag = false,
    tqKeywordFlag = true,
    commute = GetQueryString('commute'),
    arrTmpType = [],
    arrTmpMore = [],
    arrType = [] //租住类型的数据
    ,
    arrMore = [] //更多的数据
    ,
    moreFeature = '',
    moreAround = '',
    moreLeasetype = '',
    moreTag = '',
    district_code = '',
    bizcircle_code = '',
    resblock_id = '',
    resblockPoint = {
        lng: '',
        lat: ''
    },
    order_by = '' //时间 duration 价格 sellPrice 面积 size 默认为空
    ,
    sort_flag = 'desc',
    transport = 'transit',
    minute = 45,
    transtPos = {
        start: '',
        end: ''
    },
    roomListType = '',
    scrollFlag = true,
    scrollIngFlag = false,
    timer = null,
    page = 1,
    totalPage = 0,
    scaleFlag = false,
    tqCityShow = true,
    tqZoom = false,
    backCenterFlag = false;







var typeListFlag = {
    'hz': false,
    'zz': false,
    'yz': false
};
var typeOldListFlag = {
    'hz': false,
    'zz': false,
    'yz': false
};

//设置城市
setCity();
//搜索词联想
searchKeyword();
//筛选条件的一些交互
actionFn();
//登录判断
// checkLogin();

filterDate();


var filter;

function filterDate() {
    var data = {
        "code": 200,
        "message": "success",
        "data": {
           /* "leasetype": [{
                    "value": "2",
                    "title": "年租"
                },
                {
                    "value": "1",
                    "title": "短租"
                }
            ],*/
            "type": [{
                    "show": "合租",
                    "type": 1,
                    "value": "0",
                    "title": "不限"
                },
                {
                    "show": "合租一居",
                    "type": 1,
                    "value": "1",
                    "title": "1居"
                },
                {
                    "show": "合租二居",
                    "type": 1,
                    "value": "2",
                    "title": "2居"
                },
                {
                    "show": "合租三居",
                    "type": 1,
                    "value": "3",
                    "title": "3居"
                },{
                    "show": "整租",
                    "type": 2,
                    "value": "-0",
                    "title": "不限"
                },
                {
                    "show": "整租一居",
                    "type": 2,
                    "value": "-1",
                    "title": "1居"
                },
                {
                    "show": "整租二居",
                    "type": 2,
                    "value": "-2",
                    "title": "2居"
                },
                {
                    "show": "整租三居",
                    "type": 2,
                    "value": "-3",
                    "title": "3居"
                }
            ],
            "price": [{
                    "title": "不限",
                    "value": ","
                },
                {
                    "title": "1500元以下",
                    "value": ",1500"
                },
                {
                    "title": "1500-2500元",
                    "value": "1500,2500"
                },
                {
                    "title": "2500-4000元",
                    "value": "2500,4000"
                },
                {
                    "title": "4000-6000元",
                    "value": "4000,6000"
                },
                {
                    "title": "6000-8000元",
                    "value": "6000,8000"
                },
                {
                    "title": "8000-10000元",
                    "value": "8000,10000"
                },
                {
                    "title": "10000元以上",
                    "value": "10000,"
                }
            ],
            "price1": [{
                    "title": "不限",
                    "value": ","
                },
                {
                    "title": "1500元以下",
                    "value": ",1500"
                },
                {
                    "title": "1500-2000元",
                    "value": "1500,2000"
                },
                {
                    "title": "2000-2500元",
                    "value": "2000,2500"
                },
                {
                    "title": "2500-3000元",
                    "value": "2500,3000"
                },
                {
                    "title": "3000-3500元",
                    "value": "3000,3500"
                },
                {
                    "title": "3500元以上",
                    "value": "3500,"
                }
            ],
            "price2": [{
                    "title": "不限",
                    "value": ","
                },
                {
                    "title": "3000元以下",
                    "value": ",3000"
                },
                {
                    "title": "3000-4000元",
                    "value": "3000,4000"
                },
                {
                    "title": "4000-5000元",
                    "value": "4000,5000"
                },
                {
                    "title": "5000-6000元",
                    "value": "5000,6000"
                },
                {
                    "title": "6000-7000元",
                    "value": "6000,7000"
                },
                {
                    "title": "7000元以上",
                    "value": "7000,"
                }
            ],
            "sort": [{
                    "title": "默认排序",
                    "value": "1"
                },
                {
                    "title": "价格从低到高",
                    "value": "2"
                },
                {
                    "title": "价格从高到低",
                    "value": "3"
                },
                {
                    "title": "面积从小到大",
                    "value": "4"
                },
                {
                    "title": "面积从大到小",
                    "value": "5"
                }
            ],
            "face": [{
                    "value": "2",
                    "title": "南"
                },
                {
                    "value": "4",
                    "title": "北"
                },
                {
                    "value": "1",
                    "title": "东"
                },
                {
                    "value": "3",
                    "title": "西"
                }
            ],
            "hface2": [{
                    "value": "2",
                    "title": "南"
                },
                {
                    "value": "4",
                    "title": "北"
                },
                {
                    "value": "1",
                    "title": "东"
                },
                {
                    "value": "3",
                    "title": "西"
                }
            ],
            "rface1": [{
                    "value": "2",
                    "title": "南"
                },
                {
                    "value": "4",
                    "title": "北"
                },
                {
                    "value": "1",
                    "title": "东"
                },
                {
                    "value": "3",
                    "title": "西"
                }
            ],
            "feature": [{
                    "value": "5",
                    "title": "首次出租"
                },
                {
                    "value": "11",
                    "title": "独立卫生间"
                },
                {
                    "value": "12",
                    "title": "独立阳台"
                },
                {
                    "value": "7",
                    "title": "集体供暖"
                },
                {
                    "value": "8",
                    "title": "独立供暖"
                },
                {
                    "value": "9",
                    "title": "中央供暖"
                },
                {
                    "value": "14",
                    "title": "有电梯"
                }
            ],
            "feature1": [{
                    "value": "5",
                    "title": "首次出租"
                },
                {
                    "value": "11",
                    "title": "独立卫生间"
                },
                {
                    "value": "12",
                    "title": "独立阳台"
                },
                {
                    "value": "7",
                    "title": "集体供暖"
                },
                {
                    "value": "8",
                    "title": "独立供暖"
                },
                {
                    "value": "9",
                    "title": "中央供暖"
                },
                {
                    "value": "14",
                    "title": "有电梯"
                }
            ],
            "feature2": [{
                    "value": "5",
                    "title": "首次出租"
                },
                {
                    "value": "15",
                    "title": "2个卫生间"
                },
                {
                    "value": "7",
                    "title": "集体供暖"
                },
                {
                    "value": "8",
                    "title": "独立供暖"
                },
                {
                    "value": "9",
                    "title": "中央供暖"
                },
                {
                    "value": "7",
                    "title": "可养宠物"
                },
                {
                    "value": "14",
                    "title": "有电梯"
                }
            ],
            "tag": [{
                    "value": "1",
                    "title": "可立即入住"
                },
                {
                    "value": "2",
                    "title": "可预订"
                }
            ],
            "around": [{
                    "value": "13",
                    "title": "离地铁近"
                }
            ],
            "area2": [{
                    "title": "40㎡以下",
                    "value": ",40"
                },
                {
                    "title": "40-60㎡",
                    "value": "40,60"
                },
                {
                    "title": "60-80㎡",
                    "value": "60,80"
                },
                {
                    "title": "80-100㎡",
                    "value": "80,100"
                },
                {
                    "title": "100-120㎡",
                    "value": "100,120"
                },
                {
                    "title": "120㎡以上",
                    "value": "120,"
                }
            ]
        }
    };

    filter = data;
    var filterType = filter.data.type;
    //类别模板
    var filterData = {
        data: [
            {
                title: '荣者整租',
                list: []
            },
            {
                title: '业主直租',
                list: []
            }
        ]
    };
    for (var i = 0; i < filterType.length; i++) {
        if (filterType[i].type == 1 && filterType[i].value != '') {
            filterData.data[0].list.push({
                value: filterType[i].value,
                title: filterType[i].title
            });
        }
        if (filterType[i].type == 2 && filterType[i].value != '') {
            filterData.data[1].list.push({
                value: filterType[i].value,
                title: filterType[i].title
            });
        }
    }
    var newFilterData = {
        data: [

        ]
    };
    if (filterData.data[0].list.length > 0) {
        newFilterData.data[0] = filterData.data[0];
    }
    if (filterData.data[1].list.length > 0) {
        newFilterData.data[1] = filterData.data[1];
    }

    console.log(newFilterData);
    var html = template('typeListTpl', newFilterData);
    console.log(html, '**************typeListTpl*************');
    document.getElementById('J_typeList').innerHTML = html;
    //类别模板结束

    //价格
    setFilterList(filter.data.price, 'price');
    //朝向
    setFilterList(filter.data.face, 'face')
    //面积
    setFilterList(filter.data.area2, 'area');
    //特色
    setFeaturesList(filter.data.feature);
}


//通勤方式的模板
// $.get(configUrl, function (json) {

//     if (json.code == 405) {
//         tqCityShow = false;
//         J_TqBox.hide();
//     } else if (json.code == 200) {
//         tqCityShow = true;
//         tqData = json.data;
//         setTqData(tqData);
//         J_TqBox.show();
//     } else {
//         console.log(json.message);
//     }


// });

var trafficJson = {
    "code": 200,
    "message": "success",
    "data": [{
            "id": "transit",
            "name": "公交",
            "selected": 45,
            "prefered": 1,
            "sections": [
                30,
                45,
                60,
                75,
                90
            ]
        },
        {
            "id": "drive",
            "name": "驾车",
            "selected": 45,
            "prefered": 0,
            "sections": [
                30,
                45,
                60,
                75,
                90
            ]
        },
        {
            "id": "ride",
            "name": "骑行",
            "selected": 30,
            "prefered": 0,
            "sections": [
                15,
                25,
                30,
                35,
                40
            ]
        },
        {
            "id": "walk",
            "name": "步行",
            "selected": 20,
            "prefered": 0,
            "sections": [
                10,
                15,
                20,
                25,
                30
            ]
        }
    ]
};


getConfigMap(trafficJson);

function getConfigMap(json){
console.log('getconfigmap', json);

if (json.code == 405) {
    tqCityShow = false;
    J_TqBox.hide();
} else if (json.code == 200) {
    tqCityShow = true;
    tqData = json.data;
    setTqData(tqData);
    J_TqBox.show();
} else {
    console.log(json.message);
}
}

function setTqData(data) {
    var json = {
        data: data
    }
    var data = json.data;
    var html = template('tqTypeTpl', json);
    var htmls;


    document.getElementById('J_tqType').innerHTML = html;
    for (var i = 0; i < json.data.length; i++) {
        if (json.data[i].prefered == 1) {
            transport = json.data[i].id;
            J_tqType.find('li').eq(i).addClass('active').siblings().removeClass('active');

            htmls = template('tqMinTpl', json.data[i]);
            document.getElementById('J_tqMin').innerHTML = htmls;
            for (var j = 0; j < data[i].sections.length; j++) {
                if (data[i].selected == data[i].sections[j]) {
                    minute = data[i].sections[j];
                    J_tqMin.find('li').eq(j).addClass('active').siblings().removeClass('active');
                }
            }
        }
    }

};

J_tqType.delegate('li', 'click', function () {
    var val = $(this).attr('data-val');
    var index = 0;

    for (var i = 0; i < tqData.length; i++) {
        tqData[i].prefered = 0;
    }
    switch (val) {
        case 'transit':
            index = 0;
            break;
        case 'drive':
            index = 1;
            break;
        case 'ride':
            index = 2;
            break;
        case 'walk':
            index = 3;
            break;
    }
    tqData[index].prefered = 1;
    setTqData(tqData);

    transtPos = {
        start: '',
        end: ''
    };
    scaleFlag = true;
    tqZoom = true;
    resblock_id = '';
    resblockPoint = {
        lng: '',
        lat: ''
    };
    rzroomMap.mapAjax();

});
J_tqMin.delegate('li', 'click', function () {
    $(this).addClass('active').siblings().removeClass('active');
    minute = $(this).attr('data-val');
    transtPos = {
        start: '',
        end: ''
    };
    scaleFlag = true;
    tqZoom = true;
    resblock_id = '';
    resblockPoint = {
        lng: '',
        lat: ''
    };
    rzroomMap.mapAjax();
});

//租住类型的a标签点击事件
$('#J_typeList').delegate('a', 'click', function (e) {
    if ($(this).hasClass('active')) {
        $(this).removeClass('active');
    } else {
        $(this).addClass('active');
    }
    countTypeNum('typeList');
});

//更多的a标签点击事件
$('#J_moreList').delegate('a', 'click', function (e) {

    if ($(this).hasClass('checkbox')) {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active');
        }
    } else {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
        } else {
            $(this).addClass('active').siblings().removeClass('active');
        }
    }
    countTypeNum('moreList');
});

function countTypeNum(types) {
    var n = 0;
    if (types == 'typeList') {
        arrTmpType = [];
        $('#J_typeList a').each(function () {
            if ($(this).hasClass('active')) {
                n++;
                arrTmpType.push($(this).attr('data-val'));
            }
        });
        if (n == 0) {
            J_typeNum.html(n).css({
                display: 'none'
            });
        } else {
            J_typeNum.html(n).css({
                display: 'inline-block'
            });
        }

    } else {
        arrTmpMore = [];
        var tmpFeatureVal = [];
        var tmpAroundVal = [];
        var tmpLeasetypeVal = [];
        var tmpTagVal = [];

        $('[data-name="feature"],[data-name="around"],[data-name="leasetype"],[data-name="tag"]').each(function () {
            if ($(this).hasClass('active')) {
                switch ($(this).attr('data-name')) {
                    case 'feature':
                        tmpFeatureVal.push($(this).attr('data-val'));
                        break;
                    case 'around':
                        tmpAroundVal.push($(this).attr('data-val'));
                        break;
                    case 'leasetype':
                        tmpLeasetypeVal.push($(this).attr('data-val'));
                        break;
                    case 'tag':
                        tmpTagVal.push($(this).attr('data-val'));
                        break;
                }

            }

        });
        arrTmpMore.push({
            name: 'feature',
            value: tmpFeatureVal
        });
        arrTmpMore.push({
            name: 'around',
            value: tmpAroundVal
        });
        arrTmpMore.push({
            name: 'leasetype',
            value: tmpLeasetypeVal
        });
        arrTmpMore.push({
            name: 'tag',
            value: tmpTagVal
        });
        n = tmpFeatureVal.length + tmpAroundVal.length + tmpLeasetypeVal.length + tmpTagVal.length;
        if (n == 0) {
            J_moreNum.html(n).css({
                display: 'none'
            });
        } else {
            J_moreNum.html(n).css({
                display: 'inline-block'
            });
        }
    }
}
//设置租住类型的多选选项是否选中
function setTypeActive(btnType) {
    var J_typeList_a = $('#J_typeList a');

    J_typeList_a.removeClass('active');
    if (btnType == 'confirm') {
        arrType = arrTmpType;
    } else {
        arrTmpType = arrType;
    }
    typeListFlag = {
        'hz': false,
        'zz': false,
        'yz': false
    }
    for (var i = 0; i < arrType.length; i++) {
        J_typeList_a.each(function () {
            if ($(this).attr('data-val') == arrType[i]) {
                $(this).addClass('active');
            }
        });
        if (Number(arrType[i]) < 10) {
            typeListFlag.hz = true;
        }
        if (Number(arrType[i]) >= 10 && Number(arrType[i]) < 20) {
            typeListFlag.zz = true;
        }

        if (Number(arrType[i]) >= 20) {
            typeListFlag.yz = true;
        }
    }

    if (arrType.length == 0) {
        J_typeNum.html(arrType.length).css({
            display: 'none'
        });
    } else {
        J_typeNum.html(arrType.length).css({
            display: 'inline-block'
        });
    }

    if (btnType == 'confirm') {
        resblock_id = '';
        resblockPoint = {
            lng: '',
            lat: ''
        };
        scrollIngFlag = false;

        //说明之前选的是合租，现在选的不是合租了
        if (typeListFlag.hz != typeOldListFlag.hz) {
            typeOldListFlag.hz = typeListFlag.hz;
            clearFilter('more');
        }
        if (typeListFlag.zz != typeOldListFlag.zz) {
            typeOldListFlag.zz = typeListFlag.zz;
            clearFilter('more');
        }
        if (typeListFlag.yz != typeOldListFlag.yz) {
            typeOldListFlag.yz = typeListFlag.yz;
            clearFilter('more');
        }

        //当只选了合租的时候
        if (typeListFlag.hz) {
            setFilterList(filter.data.price1, 'price');
            setFeaturesList(filter.data.feature);
            J_areaListBox.hide();
            clearFilter('area');
        }
        //选了整租或业主直租的时候
        if (typeListFlag.yz || typeListFlag.zz) {
            setFilterList(filter.data.price2, 'price');
            setFeaturesList(filter.data.feature2);
            J_areaListBox.show();

        }
        if (typeListFlag.hz && typeListFlag.yz || typeListFlag.hz && typeListFlag.zz) {
            setFilterList(filter.data.price, 'price');
        }

        var tmpTypeVal = '';
        for (var i = 0; i < arrType.length; i++) {
            tmpTypeVal += arrType[i] + ',';
        }
        J_typeVal.attr('data-val', tmpTypeVal.substring(0, tmpTypeVal.length - 1));


    }
}



function setMoreActive(btnType) {
    var J_moreList_a = $('#J_moreList a');
    J_moreList_a.removeClass('active');

    var num = 0;
    if (btnType == 'confirm') {
        resblock_id = '';
        resblockPoint = {
            lng: '',
            lat: ''
        };
        scrollIngFlag = false;
        arrMore = arrTmpMore;
    } else {
        arrTmpMore = arrMore;
    }
    for (var i = 0; i < arrMore.length; i++) {
        for (var j = 0; j < arrMore[i].value.length; j++) {
            J_moreList_a.each(function () {
                if ($(this).attr('data-val') == arrMore[i].value[j] && $(this).attr('data-name') == arrMore[i].name) {
                    $(this).addClass('active');
                    num++;
                }
            });
        }
    }

    if (num == 0) {
        J_moreNum.html(num).css({
            display: 'none'
        });
    } else {
        J_moreNum.html(num).css({
            display: 'inline-block'
        });
    }

    var tmpVal = '';
    for (var i = 0; i < arrMore[0].value.length; i++) {
        tmpVal += arrMore[0].value[i] + ',';
    }
    moreFeature = tmpVal.substring(0, tmpVal.length - 1);
    tmpVal = '';
    for (var i = 0; i < arrMore[1].value.length; i++) {
        tmpVal += arrMore[1].value[i] + ',';
    }
    moreAround = tmpVal.substring(0, tmpVal.length - 1);

    tmpVal = '';
    for (var i = 0; i < arrMore[2].value.length; i++) {
        tmpVal += arrMore[2].value[i] + ',';
    }
    moreLeasetype = tmpVal.substring(0, tmpVal.length - 1);

    tmpVal = '';
    for (var i = 0; i < arrMore[3].value.length; i++) {
        tmpVal += arrMore[3].value[i] + ',';
    }
    moreTag = tmpVal.substring(0, tmpVal.length - 1);



}


//类别的取消按扭
$('#J_typeCancel').click(function () {
    setTypeActive('cancel');
});
//类别的确定按扭
$('#J_typeConfirm').click(function () {
    setTypeActive('confirm');
});


//更多的取消按扭
$('#J_cancel').click(function () {
    setMoreActive('cancel');

});
//更多的确定按扭
$('#J_confirm').click(function () {
    setMoreActive('confirm');
});


J_selectListForA.delegate('a', 'click', function (e) {
    scrollIngFlag = false;
    resblock_id = '';
    resblockPoint = {
        lng: '',
        lat: ''
    };
    var txt = $(this).attr('data-txt');
    if ($(this).attr('data-for') == 'price' && txt == '不限') {
        txt = '价格';
    }
    $('#J_' + $(this).attr('data-for') + 'Val').html(txt + ' <b><s class="ani"></s></b>').attr('data-val', $(this).attr('data-val'));
    $(this).addClass('active').siblings().removeClass('active');

});



function setFilterList(data, type) {
    var newData = {
        t: type,
        data: data
    };
    var html = template('filterListTpl', newData);
    switch (type) {
        case 'price':
            document.getElementById('J_priceList').innerHTML = html;
            break;
        case 'area':
            document.getElementById('J_areaList').innerHTML = html;
            break;
        case 'face':
            document.getElementById('J_faceList').innerHTML = html;
            break;
    };
};



function setFeaturesList(feature) {
    var featuresData = {
        data: [{
                title: '房屋特色',
                name: 'feature',
                list: feature
            },
            {
                title: '房源周边',
                name: 'around',
                list: filter.data.around
            },
            /*{
                title: '租约类型',
                name: 'leasetype',
                list: filter.data.leasetype
            },*/
            {
                title: '房屋状态',
                name: 'tag',
                list: filter.data.tag
            }
        ]
    };
    var html = template('moreListTpl', featuresData);
    document.getElementById('J_moreList').innerHTML = html;
}



function clearFilter(type) {


    if (type == 'types') {
        clearTypeList();
    }
    if (type == 'price') {
        clearPriceList();
    }
    if (type == 'face') {
        clearFaceList();
    }
    if (type == 'area') {
        clearAreaList();
    }
    if (type == 'more') {
        clearMoreList();
    }
    if (type == 'all') {
        clearTypeList();
        clearPriceList();
        clearFaceList();
        clearAreaList();
        clearMoreList();
        clearRoundMarker();
        $('#J_MyKeywords').val('');
        $('#J_keywords').val('');
        centerPoint = '';

    }
    if (type == 'allFilter') {
        clearTypeList();
        clearPriceList();
        clearFaceList();
        clearAreaList();
        clearMoreList();
        clearRoundMarker();
    }
}
//清除更多选项
function clearMoreList() {
    var J_moreList_a = $('#J_moreList a');
    for (var i = 0; i < arrMore.length; i++) {
        for (var j = 0; j < arrMore[i].value.length; j++) {
            arrMore[i].value = [];
        }
    }
    J_moreList_a.removeClass('active');
    J_moreNum.html(0).css({
        display: 'none'
    });
    moreFeature = '';
    moreAround = '';
    moreLeasetype = '';
    moreTag = '';


}

//清除面积
function clearAreaList() {
    J_QareaList.find('a').removeClass('active');
    J_areaVal.attr('data-val', '').html('面积<b class="ani"></b>');
    J_areaListBox.hide();
}
//清除价格
function clearPriceList() {
    J_QpriceList.find('a').removeClass('active');
    J_priceVal.attr('data-val', '').html('价格<b class="ani"></b>');
}
//清除朝向
function clearFaceList() {
    J_QfaceList.find('a').removeClass('active');
    J_faceVal.attr('data-val', '').html('朝向<b class="ani"></b>');
}
//清除租住类型
function clearTypeList() {
    J_QtypeList.find('a').removeClass('active');
    arrType = [];
    J_typeNum.html(0).hide();
    J_typeVal.attr('data-val', '');
}

//清除周边marker
function clearRoundMarker() {
    //$('.roundMarkers').remove();
    J_round.removeClass();
    J_roundName.html('周边');
    J_roundList.find('a').removeClass('active');
    roundTxt = '';
}


//获取URL里的参数值方法
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}
//关键字搜索
function searchKeyword() {
    var step = -1;
    var oldValue = "";
    var oInput = J_Mykeywords,
        oBox = $('#ajaxBox'),
        oUl = $('#suggestion'),
        aLi = oUl.find('li');

    $(document).click(function () {
        oBox.hide();
        myKeywordFlag = false;
    });

    oInput.keyup(function (ev) {

        myKeywordFlag = true;

        var oEvent = ev || event;
        var oTxt = $.trim(oInput.val());

        if (oTxt == '') {
            oBox.hide();
            $('#J_KeywordMakers').remove();
            centerPoint = '';
            return;
        }

        if (oEvent.keyCode == 38 || oEvent.keyCode == 40) {
            return;
        }

        if (oEvent.keyCode == 13) {

            var aLi = oUl.find('li');
            if (step < 0) {
                step = 0;
            }

            if (aLi.length > 0) {
                oInput.val(aLi.eq(step).text());
                centerPoint = aLi.eq(step).attr('data-lng') + ',' + aLi.eq(step).attr('data-lat');
                resblock_id=aLi.eq(step).attr('data-code');
                $('#townId').val(aLi.eq(step).attr('data-townid'));
            }
            map.centerAndZoom(new BMap.Point(centerPoint.split(',')[0], centerPoint.split(',')[1]), 16);
            oUl.html('');
            oBox.hide();
            return;
        }


        if ($.trim(oInput.val()) == '') {
            oBox.hide();
            oUl.html('');
        }
        $.get(suggestionUrl + '' + encodeURIComponent(oTxt), function (json) {
            var newData = json.data;
            console.log("------------->suggerst---"+newData.length);
            if (newData.length > 0) {
                var _html = '';
                var lng = 0;
                var lat = 0;
                for (var i = 0; i < newData.length; i++) {
                    lat = newData[i].latitude;
                    lng = newData[i].longitude;
                    _html += '<li data-lng="' + lng + '" data-lat="' + lat + '" data-name="' + newData[i].name + '" data-code="'+newData[i].code+'" data-townid="'+newData[i].townId+'">' + newData[i].name + '</li>';
                }
                oUl.html(_html);
                oBox.show();
            }
        });

        oldValue = oTxt;
        step = -1;
    });
    oUl.delegate('li', 'click', function () {
        myKeywordFlag = true;
        oInput.val($(this).text());
        centerPoint = $(this).attr('data-lng') + ',' + $(this).attr('data-lat');
        resblock_id=$(this).attr('data-code');
        $('#townId').val($(this).attr('data-townid'));
        map.centerAndZoom(new BMap.Point($(this).attr('data-lng'), $(this).attr('data-lat')), 16);
    });
    oInput.keydown(function (ev) {
        var oEvent = ev || event;

        if (oEvent.keyCode == 40) //↓
        {
            var aLi = oUl.find('li');
            step++;
            if (step == aLi.length) {
                step = -1;
            }
            aLi.removeClass("keyhover");
            if (step != -1) {
                aLi.eq(step).addClass("keyhover");
                oInput.val(aLi.eq(step).text());
            } else {
                oInput.val(oldValue);
            }
        } else if (oEvent.keyCode == 38) {
            var aLi = oUl.find('li');
            step--;
            if (step == -2) {
                step = aLi.length - 1;
            }
            aLi.removeClass("keyhover");
            if (step != -1) {
                aLi.eq(step).addClass("keyhover");
                oInput.val(aLi.eq(step).text());
            } else {
                oInput.val(oldValue);
            }
        }
        if (oEvent.keyCode == 38 || oEvent.keyCode == 40) {
            return false;
        }
    });
    aLi.live("mouseover mouseout", function (event) {
        aLi.removeClass("keyhover");
        if (event.type == 'mouseover') {
            $(this).addClass("keyhover");
            step = $(this).index();
        } else {
            $(this).removeClass("keyhover");
            step = $(this).index();
        }
    });
}

//$(document).pjax('a[data-pjax]', '#wrapper');
//设置城市
function setCity() {
    var cityLink = [
        {
            name: '重庆',
            url: baseUrl,
            lng: 106.5049620,
            lat: 29.5331550,
            cityId:5001
        }
    ];



    var cityIndex = 0;
console.log("current url----"+curUrl);
    switch (curUrl) {
        case cityLink[0].url:
            cityIndex = 0;
            break;
    }


    RZCONFIG = {
        cityName: cityLink[cityIndex].name,
        url: cityLink[cityIndex].url,
        lng: cityLink[cityIndex].lng,
        lat: cityLink[cityIndex].lat,
        cityId:cityLink[cityIndex].cityId
    };

    $('#curCityName').html(cityLink[cityIndex].name);
    $('#cityId').val(cityLink[cityIndex].cityId);

    var _html = '';
    var classActive = '';

    for (var i = 0; i < cityLink.length; i++) {
        if (i == cityIndex) {
            classActive = "active";
        } else {
            classActive = '';
        }
        _html += '<a href="' + cityLink[i].url + '/map/?cityId="'+cityLink[i].cityId+'class=' + classActive + '">' + cityLink[i].name + '<b><s class="ani"></s></b></a>';
    }
    $('#cityList').html(_html);
}
//筛选条件的一些交互
function actionFn() {
    aSelectList.each(function () {
        var _this = $(this);
        $(this).find('dt').click(function (e) {
            if (!J_bgShadow.is(':visible')) {
                J_bgShadow.show();
            }
            _this.find('dd').css({
                top: '40px'
            });
            _this.siblings().find('dd').css({
                top: '-500px'
            }).removeClass('shadow');
            _this.addClass('selectList_hover').siblings().removeClass('selectList_hover');
            setTimeout(function () {
                _this.find('dd').addClass('shadow');
            }, 200);
            e.stopPropagation();
        });
    });

    $('body').delegate('#J_moreList,#J_typeList', 'click', function (e) {
        e.stopPropagation();
    });


    $(document).click(function () {
        hideSel();
    });


    function hideSel() {
        J_bgShadow.hide();
        aSelectList.removeClass('selectList_hover');
        aSelectList.find('dd').css({
            top: '-500px'
        }).removeClass('shadow');
    }

    function toSetHeight() {
        var winHeight = $(window).height();
        var winWidth = $(window).width();
        var headerHeight = $('#header').height();
        var selectHeight = $('#selectBox').height();
        var h = winHeight - headerHeight - selectHeight;
        J_keywords.css({
            width: (winWidth - 371) + 'px'
        })
        J_bgShadow.css({
            'height': h + 'px',
            'top': (headerHeight + selectHeight) + 'px'
        });
        $('#content').css({
            'height': h + 'px'
        });
        oScrollContent.css({
            'height': h - 80 + 'px'
        });
    }

    toSetHeight();
    $(window).resize(function () {
        toSetHeight();
    });

}
/*************************************地图的一些操作*********************************************/


// 百度地图API功能
var map = new BMap.Map("allmap", {
    enableMapClick: false,
    minZoom: 11,
    maxZoom: 18
}); // 创建Map实例
var myKeywordIcon = new BMap.Icon("http://10.30.24.16:3000/img/location.png", new BMap.Size(30, 40));
var tqKeywordIcon = new BMap.Icon("http://10.30.24.16:3000/img/tqPos.png", new BMap.Size(106, 80));
var myRoundIcon = new BMap.Icon("http://10.30.24.16:3000/img/markers_round.png", new BMap.Size(21, 33));
var myLineIcon = new BMap.Icon("http://lbsyun.baidu.com/jsdemo/img/location.gif", new BMap.Size(2, 2));
var geoc = new BMap.Geocoder();
var routePolicy = [BMAP_DRIVING_POLICY_LEAST_TIME, BMAP_DRIVING_POLICY_LEAST_DISTANCE, BMAP_DRIVING_POLICY_AVOID_HIGHWAYS];
//驾车
var driving = new BMap.DrivingRoute(map, {
    renderOptions: {
        map: map,
        autoViewport: false
        // ,panel: "r-result"
    },
    onPolylinesSet: function () {
        housePoint = [];
        $('[stroke="#0030ff"]').each(function () {
            $(this).attr({
                'stroke': '#4EB1FF',
                'stroke-width': 6,
                'stroke-opacity': 1
            });
        });
    }

});
//步行
var walking = new BMap.WalkingRoute(map, {
    //strokeColor:"blue", strokeWeight:6, strokeOpacity:1,
    renderOptions: {
        map: map,
        autoViewport: false
        // ,panel: "r-result"
    },
    onPolylinesSet: function () {
        housePoint = [];
        $('[stroke="#30a208"]').each(function () {
            $(this).attr({
                'stroke': '#4EB1FF',
                'stroke-width': 6,
                'stroke-opacity': 1
            });
        });
    }
});
//公交车

var transit = new BMap.TransitRoute(map, {
    renderOptions: {
        map: map,
        autoViewport: false
        //,panel: "r-result"
    },
    pageCapacity: 1,
    policy: 1,
    onPolylinesSet: function () {


        $('[stroke="#fff"]').remove();
        $('[stroke="#30a208"]').each(function () {
            $(this).attr({
                'stroke': '#4EB1FF',
                'stroke-width': 6,
                'stroke-opacity': 1
            });
        });
        $('[stroke="#0030ff"]').each(function () {
            $(this).attr({
                'stroke': '#4EB1FF',
                'stroke-width': 6,
                'stroke-opacity': 1
            });
        });



    }
});
var bdary = new BMap.Boundary();
map.centerAndZoom(new BMap.Point(RZCONFIG.lng, RZCONFIG.lat), 11); // 初始化地图,设置中心点坐标和地图级别
map.setCurrentCity(RZCONFIG.cityName); // 设置地图显示的城市 此项是必须设置的
map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放

var ac = new BMap.Autocomplete({
    "input": "J_keywords",
    "location": map
});

ac.addEventListener("onconfirm", function (e) { //鼠标点击下拉列表后的事件
    var _value = e.item.value;
    myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
    var txt = _value.province + _value.district + _value.street + _value.business;
    rzroomMap.setPlace(txt);
});


var J_TqLeft = $('#J_TqLeft'), //通勤左边选项
    J_TqRightBtn = $('#J_TqRightBtn'), //打开关闭通勤按扭
    J_getDistance = $('#J_getDistance'), //测距按扭
    keywordPoint = [], //关键字坐标
    housePoint = [],
    mapZoom = 12,
    plyObj = {}, //行政区划对像
    ply = null,
    roundTxt = '', //周边关键词
    markerKeyword = null, //关键字marker
    local = null, //当前区域搜索
    localOptions = null; //搜索参数


var rzroomMap = {
    mapInit: function () {
        var _this = this;

        J_keywords.keyup(function (ev) {
            var oEvent = ev || event;
            var keyCode = oEvent.keyCode;
            var txt = $.trim($(this).val());
            if (keyCode == 13 && txt == '') {
                $('.keywordMakers').remove();
                $('[stroke="#018EFF"]').remove();
                keywordPoint = [];
            }
            $('.tangram-suggestion-main').css({
                'z-index': 11
            });
        });

        map.addEventListener("zoomstart", function () {
            map.clearOverlays();
        });

        map.addEventListener("zoomend", function () {
            page = 1;
            district_code = '';
            bizcircle_code = '';
            //resblock_id='';
            scrollIngFlag = false;
            if (!tqFlag) {
                resblock_id = '';
            }
            if (!tqZoom || !backCenterFlag) {
                _this.mapAjax();


            }


            if (J_getDistance.hasClass('active')) {
                J_getDistance.removeClass('active');
            }


            if (tqDragFlag) {

                geoc.getLocation(map.getCenter(), function (rs) {
                    var addComp = rs.addressComponents;
                    var _val = addComp.district + "" + addComp.street + "" + addComp.streetNumber;
                    J_keywords.val(_val);

                    $('.tangram-suggestion-main').css({
                        'z-index': -1
                    });

                });

            }


        });
        map.addEventListener("moveend", function () {
            page = 1;
            district_code = '';
            bizcircle_code = '';
            //resblock_id='';
            scrollIngFlag = false;
            if (!tqFlag) {
                resblock_id = '';
            }
            if (!tqZoom || !backCenterFlag) {
                _this.mapAjax();
            }
            if (J_getDistance.hasClass('active')) {
                J_getDistance.removeClass('active');
            }
            //console.log('tqDragFlag='+tqDragFlag);
            if (tqDragFlag) {

                geoc.getLocation(map.getCenter(), function (rs) {
                    var addComp = rs.addressComponents;
                    var _val = addComp.district + "" + addComp.street + "" + addComp.streetNumber;
                    J_keywords.val(_val);
                    $('.tangram-suggestion-main').css({
                        'z-index': -1
                    });

                });

            }
        });



    },
    //打开通勤
    setShowTqBox: function () {
        var _this = this;
        J_TqLeft.stop().animate({
            'margin-left': '0px'
        }, 500);
        J_TqRightBtn.html('关闭通勤找房');
        J_Mykeywords.css({
            'z-index': 1
        });
        J_keywords.css({
            'z-index': 2
        });

        tqZoom = true;
        if (centerPoint != '') {
            J_keywords.val($('#J_MyKeywords').val());
            J_centerTqMarker.hide();
            tqDragFlag = false;
            tqFlag = true;

            $('.tangram-suggestion-main').css({
                'z-index': -1
            });
        } else {

            tqDragFlag = true;
            map.clearOverlays();
            J_centerTqMarker.show();

            geoc.getLocation(map.getCenter(), function (rs) {
                var addComp = rs.addressComponents;
                var _val = addComp.district + "" + addComp.street + "" + addComp.streetNumber;
                J_keywords.val(_val);
                $('.tangram-suggestion-main').css({
                    'z-index': -1
                });
            });


        }


        scaleFlag = true;
        _this.mapAjax();

        tqFlag = true;

    },
    //关闭通勤找房
    setHideTqBox: function () {
        J_TqLeft.stop().animate({
            'margin-left': '-500px'
        }, 500);
        J_TqRightBtn.html('打开通勤找房');
        J_Mykeywords.css({
            'z-index': 2
        }).val(J_keywords.val());
        J_keywords.css({
            'z-index': 1
        }).val(J_Mykeywords.val());

        J_centerTqMarker.hide();
        centerPoint = '';
        $('.keywordMakers').remove();
        this.mapAjax();
        tqZoom = false;
        tqDragFlag = false;
        tqFlag = false;
    },
    //设置搜索框关键字显示
    setPlace: function (txt) {
        var _this = this;
        //this.getMapZoom();

        //map.clearOverlays();       

        local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: function () {
                if (local.getResults().getPoi(0)) {
                    var pp = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
                } else {
                    alert('请重新选择地址');
                    J_keywords.val('').focus();
                    return;
                }


                $('#J_MyKeywords').val($('#J_keywords').val());
                J_centerTqMarker.hide();

                tqDragFlag = false;
                tqFlag = true;

                centerPoint = pp.lng + ',' + pp.lat;

                map.centerAndZoom(pp, map.getZoom());
                _this.mapAjax();

            }
        });
        local.search(myValue);
    },

    getMapZoom: function () {
        mapZoom = map.getZoom();
        return mapZoom;
    },
    getMapBround: function () {
        var bounds = map.getBounds();
        var sw = bounds.getSouthWest();
        var ne = bounds.getNorthEast();
        var sw_lng = sw.lng; //最西经度
        var sw_lat = sw.lat; //最南纬度
        var ne_lng = ne.lng; //最东经度
        var ne_lat = ne.lat; //最北纬度
        var boundsArray = [sw_lng, ne_lng, sw_lat, ne_lat];
        return boundsArray;
    },
    //测距功能
    getDistance: function (a) {
        var t = new BMapLib.DistanceTool(map);
        a.on("click", function () {
            if (a.hasClass("active")) {
                t.close();
                a.removeClass("active");
            } else {
                t.open();
                a.addClass("active");
            }
        }), t.addEventListener("drawend", function (e) {
            e.points instanceof Array && !e.points.length && (a.removeClass("active"), t.close());

        }), t.addEventListener("removepolyline", function () {
            a.removeClass("active"), t.close();
        });
    },
    //周边的事件
    setRound: function () {
        var _this = this;

        var txt = '';
        J_round.hover(function () {
            $(this).addClass('hover');
        }, function () {
            $(this).removeClass('hover');
        });

        J_roundList.find('a').click(function () {

            if ($(this).hasClass('active')) {
                return;
            }

            txt = $(this).attr('data-value');
            if (txt == '') {
                txt = '周边';
                J_round.removeClass('active');
            } else {
                J_round.addClass('active');
            }
            $('.roundMarkers').remove();
            _this.setRoundMarker(txt);
            $(this).addClass('active').siblings().removeClass();
            J_roundName.html(txt);
            J_round.removeClass('hover');
        });
    },
    //设置周边的marker
    setRoundMarker: function (txt) {
        var _this = this;
        var marker;
        localOptions = {
            onSearchComplete: function (results) {

                roundTxt = txt;
                if (local.getStatus() == BMAP_STATUS_SUCCESS) { // 判断状态是否正确


                    for (var i = 0; i < results.vr.length; i++) {
                        marker = new ComplexCustomOverlay(results.vr[i].point, results.vr[i].title, 0, 'roundMarkers');
                        map.addOverlay(marker); // 将标注添加到地图中
                    }


                }
            }
        };
        var pStart = map.getBounds().getSouthWest(); //可视区域左下角
        var pEnd = map.getBounds().getNorthEast(); //可视区域右上角
        var bs = new BMap.Bounds(pStart, pEnd); //自己规定范围

        local = new BMap.LocalSearch(map, localOptions);
        local.searchInBounds(txt, bs);
    },
    //行政区划
    getBoundary: function (city, area, index) {


        bdary.get(city + '市' + area , function (rs) { //获取行政区域
            var count = rs.boundaries.length; //行政区域的点有多少个
            console.log(city+'市'+area+'获取当前输入行政区域'+count+'个');
            if (count === 0) {
                return;
            }

            var pointArray = [];
            for (var i = 0; i < count; i++) {
                ply = new BMap.Polygon(rs.boundaries[i], {
                    strokeWeight: 2,
                    strokeColor: "#FF6262",
                    strokeOpacity: 1,
                    fillColor: '#FF6262',
                    fillOpacity: '0.1'
                }); //建立多边形覆盖物
                plyObj['n_' + index + '_' + i] = ply;

                map.addOverlay(ply); //添加覆盖物

                pointArray = pointArray.concat(ply.getPath());
                ply.hide();
            }

        });
    },
    //清除覆盖物
    removeOverlay: function () {
        map.clearOverlays();
    },
    setKeyworldMarker: function (lng, lat) {

        var _this = this;
        var pt = new BMap.Point(lng, lat);

        myKeywordFlag = true;
        //当有搜索框的工作地中心点坐标，并且是第一次的时候，到地图中心点
        if (tqKeywordFlag) {
            map.centerAndZoom(pt, map.getZoom());
            tqKeywordFlag = false;
        }

        if (!tqFlag && tqCityShow) {
            markerKeyword = new ComplexCustomOverlay(pt, '在这里上班 >', 0, 'keywordMakers');
        } else {
            markerKeyword = new ComplexCustomOverlay(pt, '', 0, 'keywordMakersSmall');
        }

        map.addOverlay(markerKeyword);

        centerPoint = lng + ',' + lat;
        tqDragFlag = false;

        $('#J_KeywordMakers').click(function () {

            if (tqCityShow) {
                tqFlag = true;
                tqDragFlag = false;

                _this.setShowTqBox();
                _this.mapAjax();
            }

        });
    },
    //左下角的放大、缩小、回到中心点、测试距离功能
    slideDn: function (obj) {
        var a = obj,
            t = map.getZoom(),
            e = a.attr("id");
        switch (e) {
            case "zoomin":
                18 > t && map.setZoom(t + 1);
                break;

            case "zoomout":
                t > 11 && map.setZoom(t - 1);
                break;


        }
    },

    //通勤的事件
    tongqinFn: function () {
        var _this = this;

        var J_MyKeywords = $('#J_MyKeywords');
        J_TqLeft.find('li').click(function () {
            $(this).addClass('active').siblings().removeClass('active');
        });


        J_TqRightBtn.click(function () {


            tqZoom = false;



            if ($(this).text() == '打开通勤找房') {
                $(this).text('关闭通勤找房');
                _this.setShowTqBox();


            } else {
                $(this).text('打开通勤找房');
                transtPos = {
                    start: '',
                    end: ''
                }
                tqDragFlag = false;
                tqFlag = false;
                resblock_id = '';
                _this.setHideTqBox();
                _this.mapAjax();
            }


        });

        J_centerTqMarker.click(function () {
            map.centerAndZoom(map.getCenter(), map.getZoom());
            centerPoint = map.getCenter().lng + ',' + map.getCenter().lat;
            J_centerTqMarker.hide();
            tqDragFlag = false;
            tqFlag = true;
            _this.mapAjax();
        });

        $('body').delegate('#J_tqCloseMarker', 'click', function () {

            map.centerAndZoom(new BMap.Point($(this).attr('data-point').split(',')[0], $(this).attr('data-point').split(',')[1]), map.getZoom());
            $('.keywordMakers').remove();
            J_centerTqMarker.show();
            tqDragFlag = true;
        });

    },
    mapAjax: function () {

        var _this = this;
        var boundsArray = _this.getMapBround();
        var center = map.getCenter();
        var _url = '';



        if (backCenterFlag) {
            tqDragFlag = true;
        }

        if (tqDragFlag) {
            return;
        }



        if (ajaxFlag) {
            ajaxFlag = false;
        } else {
            return;
        }



        if (centerPoint != '') {
            center = {
                lng: centerPoint.split(',')[0],
                lat: centerPoint.split(',')[1]
            }
        }

        if (tqFlag) {
            _url = tqMapUrl;

            J_tips.show();
        } else {
            J_tips.hide();
            _url = mapUrl;
        }

        var jsonData = _url +
            '?min_lng=' + boundsArray[0] +
            '&max_lng=' + boundsArray[1] +
            '&min_lat=' + boundsArray[2] +
            '&max_lat=' + boundsArray[3] +
            '&clng=' + center.lng +
            '&clat=' + center.lat;


        if (tqZoom) {
            jsonData += '&zoom=0';
            setTimeout(function () {
                tqZoom = false;
            }, 100);
        } else {
            jsonData += '&zoom=' + map.getZoom()+'&cityId='+RZCONFIG.cityId+'&countyId='+$('#countyId').val()+'&townId='+$('#townId').val();
        }


        if (tqFlag) {
            if (transport != '') {
                jsonData += '&transport=' + transport;
            }
            if (minute != 0) {
                jsonData += '&minute=' + minute;
            }
        }

        if (J_priceVal.attr('data-val')) {
            jsonData += '&price=' + J_priceVal.attr('data-val');
        }
        if (J_faceVal.attr('data-val')) {
            jsonData += '&face=' + J_faceVal.attr('data-val')
        }
        if (J_areaVal.attr('data-val')) {
            jsonData += '&area=' + J_areaVal.attr('data-val')
        }
        if (J_typeVal.attr('data-val')) {
            jsonData += '&type=' + J_typeVal.attr('data-val');
        }

        if (moreFeature) {
            jsonData += '&feature=' + moreFeature;
        }
        if (moreAround) {
            jsonData += '&around=' + moreAround;
        }
        if (moreLeasetype) {
            jsonData += '&leasetype=' + moreLeasetype;
        }
        if (moreTag) {
            jsonData += '&tag=' + moreTag;
        }




        clearTimeout(timer);
        //J_mainLoading.show();
        $.get(jsonData, function (json) {
            handleRoomCount(json);
        });

        function handleRoomCount(json) {
            console.log(json, '************roomCount*********');
            if (json.length!=0) {
                if (J_priceVal.attr('data-val') || J_faceVal.attr('data-val') || J_areaVal.attr('data-val') || J_typeVal.attr('data-val') || moreFeature || moreAround || moreLeasetype || moreTag) {
                    J_clear.show();
                } else {
                    J_clear.hide();
                }


                timer = setTimeout(function () {
                    ajaxFlag = true;
                    backCenterFlag = false;
                }, 100);

                map.clearOverlays();
                //J_mainLoading.hide();
                var data = json;

                if (roundTxt != '') {
                    _this.setRoundMarker(roundTxt);
                }

                var marker;

                //console.log('返回的scale是='+data.scale);
                console.log('当前的scale是='+map.getZoom());

                if (!tqFlag) { //不是通勤时候的渲染
                    transtPos = {
                        start: '',
                        end: ''
                    };
                    for (var i = 0; i < data.length; i++) {
                        if (map.getZoom() <= 13) {

                            marker = new ComplexCustomOverlay({
                                lng: data[i].lon,
                                lat: data[i].lat
                            }, data[i].name + '|' + data[i].count + '套', i, 'areaMarkers', data[i].code,data[i].cityId,data[i].countyId,data[i].townId);
                            map.addOverlay(marker); // 将标注添加到地图中
                            _this.getBoundary(RZCONFIG.cityName, data[i].name, i);
                        } else if (map.getZoom() >= 14 && map.getZoom() <= 15) {

                            marker = new ComplexCustomOverlay({
                                lng: data[i].lon,
                                lat: data[i].lat
                            }, data[i].name + '|' + data[i].count + '套', i, 'businessMarkers', data[i].code,data[i].cityId,data[i].countyId,data[i].townId);
                            map.addOverlay(marker); // 将标注添加到地图中
                        } else if (map.getZoom() >= 16) {
                            marker = new ComplexCustomOverlay({
                            //(point, text, index, type, code,cityId,countyId,townId)
                                lng: data[i].lon,
                                lat: data[i].lat
                            }, data[i].name + ' ￥' + data[i].sellPrice + '|' + data[i].count + '间', i, 'houseMarkers', data[i].code,data[i].cityId,data[i].countyId,data[i].townId);
                            map.addOverlay(marker); // 将标注添加到地图中

                        }
                    }
                } else { //是通勤时候的渲染


                    tqDragFlag = false;

                    //console.log('返回的scale是='+data.scale);

                    if (map.getZoom != data.scale && scaleFlag) {
                        map.centerAndZoom(new BMap.Point(centerPoint.split(',')[0], centerPoint.split(',')[1]), data.scale);
                        scaleFlag = false;
                    }
                    for (var i = 0; i < data.length; i++) {
                        if (map.getZoom() <= 13) {
                            // transtPos={start:'',end:''};
                            marker = new ComplexCustomOverlay({
                                lng: data[i].lon,
                                lat: data[i].lat
                            }, data[i].name + '|' + data[i].count + '套', i, 'areaMarkers', data[i].code,data[i].cityId,data[i].countyId,data[i].townId);
                            map.addOverlay(marker); // 将标注添加到地图中
                            _this.getBoundary(RZCONFIG.cityName, data[i].name, i);

                        } else if (map.getZoom() >= 14 && map.getZoom() <= 15) {
                            //  transtPos={start:'',end:''};
                            marker = new ComplexCustomOverlay({
                                lng: data[i].lon,
                                lat: data[i].lat
                            }, data[i].name + '|' + data[i].count + '套', i, 'areaMarkers', data[i].code,data[i].cityId,data[i].countyId,data[i].townId);
                            map.addOverlay(marker); // 将标注添加到地图中
                        } else if (map.getZoom() >= 16) {
                            marker = new ComplexCustomOverlay({
                                lng: data[i].lon,
                                lat: data[i].lat
                            }, data[i].name + ' ￥' + data[i].sellPrice + '|' + data[i].count + '间', i, 'houseMarkers', data[i].code,data[i].cityId,data[i].countyId,data[i].townId);
                            map.addOverlay(marker); // 将标注添加到地图中

                            if (resblock_id != '') {
                                $('.houseMarkers').each(function () {
                                    if ($(this).attr('data-code') == resblock_id) {
                                        $(this).addClass('houseMarkersActive');
                                    }
                                });
                            }


                        }
                    }

                    if (transtPos.start.lng != '' && data.length > 0 && resblock_id != '') {
                        checkLine(transtPos.start, transtPos.end);

                        if (map.getZoom() <= 15 && resblockPoint.lng != '') {
                            //(point, text, index, type, code,cityId,countyId,townId)
                            marker = new ComplexCustomOverlay({
                                lng: resblockPoint.lng,
                                lat: resblockPoint.lat
                            }, '', 0, 'keywordMakersRed', '');
                            map.addOverlay(marker); // 将标注添加到地图中 
                        }

                    }




                    var largeDistance = 0;
                    var centerPointObj = {
                        lng: centerPoint.split(',')[0],
                        lat: centerPoint.split(',')[1]
                    };
                    var curPointObj = {
                        lng: data.farthest_lng,
                        lat: data.farthest_lat
                    };
                    largeDistance = getDistance(centerPointObj, curPointObj) + 500;

                    var ovalCircle = new BMap.Circle({
                        lng: centerPoint.split(',')[0],
                        lat: centerPoint.split(',')[1]
                    }, largeDistance, {
                        strokeColor: "#018EFF",
                        strokeWeight: 2,
                        strokeOpacity: 1,
                        fillColor: '#4fc1ff',
                        fillOpacity: '0.1'
                    });
                    map.addOverlay(ovalCircle);
                }

            } else {
                timer = setTimeout(function () {
                    ajaxFlag = true;
                    backCenterFlag = false;
                }, 100);
                console.log('地图接口，状态信息为：' + json.message);
            }

            if (centerPoint != '') {
                _this.setKeyworldMarker(centerPoint.split(',')[0], centerPoint.split(',')[1]);
            }
        }

        // $.get(jsonData, function(json) {});
        _this.roomAjax();
    },
    roomAjax: function () {
        var _this = this;
        var boundsArray = _this.getMapBround();
        var center = map.getCenter();
        console.log("--------------------------"+center);
        var _url = roomUrl;
        if (tqFlag) {
            _url = tqRoomUrl;
        } else {
            _url = roomUrl;
        }

        if (centerPoint != '') {
            center = {
                lng: centerPoint.split(',')[0],
                lat: centerPoint.split(',')[1]
            }
        }

        var jsonData = _url +
            '?min_lng=' + boundsArray[0] +
            '&max_lng=' + boundsArray[1] +
            '&min_lat=' + boundsArray[2] +
            '&max_lat=' + boundsArray[3] +
            '&clng=' + center.lng +
            '&clat=' + center.lat +
            '&zoom=' + map.getZoom();



        if (scrollIngFlag) { //滚动条加载++
            // jsonData+='&p='+page;
        } else { //正常从第一页开始加加
            page = 1;
            // jsonData+='&p=1';
        }
        jsonData += '&p=' + page;


        if (order_by != '') {
            jsonData += '&orderStr=' + order_by;
            jsonData += '&order=' + sort_flag;
        }
        if (district_code != '') {
            bizcircle_code = '';
            resblock_id = '';
            resblockPoint = {
                lng: '',
                lat: ''
            };
            jsonData += '&district_code=' + district_code;
        }
        if (bizcircle_code != '') {
            district_code = '';
            resblock_id = '';
            resblockPoint = {
                lng: '',
                lat: ''
            };
            jsonData += '&bizcircle_code=' + bizcircle_code;

        }
        if (resblock_id != '') {
            bizcircle_code = '';
            district_code = '';
            jsonData += '&resblock_id=' + resblock_id;
        }
        if (tqFlag) {
            jsonData += '&transport=' + transport
            jsonData += '&minute=' + minute
        }
        if (J_priceVal.attr('data-val')) {
            jsonData += '&price=' + J_priceVal.attr('data-val');
        }
        if (J_faceVal.attr('data-val')) {
            jsonData += '&face=' + J_faceVal.attr('data-val')
        }
        if (J_areaVal.attr('data-val')) {
            jsonData += '&area=' + J_areaVal.attr('data-val')
        }
        if (J_typeVal.attr('data-val')) {
            jsonData += '&type=' + J_typeVal.attr('data-val');
        }
        if (moreFeature) {
            jsonData += '&feature=' + moreFeature;
        }
        if (moreAround) {
            jsonData += '&around=' + moreAround;
        }
        if (moreLeasetype) {
            jsonData += '&leasetype=' + moreLeasetype;
        }
        if (moreTag) {
            jsonData += '&tag=' + moreTag;
        }
        var towValue='';
        if(map.getZoom()>=16){
            towValue=$('#townId').val();
        }
        jsonData+='&cityId='+RZCONFIG.cityId+'&countyId='+$('#countyId').val()+'&townId='+towValue;
        scrollFlag = false;

        /**
         * 加载
         */
            //encodeURIComponent(jsonData)
            console.log("jsonData  list------"+jsonData);
            $.get(jsonData, function (json) {
                //var newData = json.data;
                //if (json.data.length > 0) {
                    // console.log("------------->suggerst---"+newData[0].name);
                    // var _html = '';
                    // var lng = 0;
                    // var lat = 0;
                    // for (var i = 0; i < newData.length; i++) {
                    //     lat = newData[i].location.lat;
                    //     lng = newData[i].location.lon;
                    //     _html += '<li data-lng="' + lng + '" data-lat="' + lat + '" data-name="' + newData[i].name + '">' + newData[i].name + '</li>';
                    // }
                    // oUl.html(_html);
                    // oBox.show();
                    listDataHandle(json);
               // }
            });

        function listDataHandle(data) {
            console.log(data, '***********list***********');
            if (data.length!=0) {
                totalPage = 1;
               /* if (page != 1 && json.data.rooms.length == 0) {
                    J_noneHouse.show();
                }

                if (tqFlag) {
                    for (var i = 0; i < json.length; i++) {
                        json.data.rooms[i].subway = json.data.rooms[i].commute;
                    }
                }*/

                var html = template('houseListTpl', data);
                if (!scrollIngFlag) {

                    J_houseList.html(html);

                    if (page != 1 && html == '') {
                        setTimeout(function () {
                            J_noneHouse.hide();
                        }, 100);
                    }
                    oScrollContent.mCustomScrollbar("scrollTo", "0px", {
                        scrollInertia: 0
                    });

                } else {
                    J_loading.fadeOut(500);
                    if (page != 1 && data.length == 0) {
                        setTimeout(function () {
                            J_noneHouse.hide();
                        }, 100);
                    } else {
                        J_houseList.append(html);
                    }
                }
                scrollFlag = true;

            } else {
                console.log('左边房源接口，状态信息为：' + json.message);
                scrollFlag = true;
            }
        }
        // $.get(jsonData, function(json) {});
    },
    init: function () {




        var _this = this;



        oScrollContent.mCustomScrollbar({
            scrollEasing: "none",
            scrollInertia: 0,
            advanced: {
                updateOnContentResize: true,
                updateOnImageLoad: true
            },
            callbacks: {
                //onTotalScroll: function(){
                onScroll: function () {

                    var oldTop = J_houseList.height() - oScrollContent.height();
                    var curTop = Math.abs(parseInt($('#mCSB_1_container').css('top'))) + 300;

                    scrollIngFlag = true;

                    if (curTop >= oldTop) {

                        if (page < totalPage && scrollFlag) {
                            page++;

                            J_loading.show();
                            _this.roomAjax();
                        }

                    }


                }
            }
        });

        _this.mapInit(); //地图初始化
        _this.setRound();

        // _this.roomAjax();

        if (commute == 1) {
            J_TqRightBtn.text('关闭通勤找房');
            _this.setShowTqBox();
            tqFlag = false;
            _this.roomAjax();
        } else {
            _this.mapAjax();
        }

        _this.tongqinFn(); //通勤

        $('#J_slideLeft a').click(function () {
            _this.slideDn($(this)); //左下角的事件
        });



        _this.getDistance(J_getDistance); //测距



        //排序事件
        J_sortingList.find('li').click(function () {
            scrollIngFlag = false;
            if ($(this).attr('data-flag') == 'desc') {
                $(this).attr('data-flag', 'asc');
            } else {
                $(this).attr('data-flag', 'desc');
            }


            if (tqFlag) {
                order_by = $.trim($(this).attr('data-type'));

                sort_flag = $(this).attr('data-flag');
            } else {
                if ($.trim($(this).attr('data-type')) == 'duration') {
                    order_by = '';
                    sort_flag = '';

                } else {
                    order_by = $(this).attr('data-type');
                    sort_flag = $(this).attr('data-flag');
                }

            }


            $(this).siblings().attr('data-flag', 'desc');
            $(this).addClass('active').siblings().removeClass('active');
            _this.roomAjax();
        });


        $('body').delegate('.J_toAjax', 'click', function () {
            if ($(this).attr('id') == 'J_BackCenter') {
                clearFilter('allFilter');
                clearFilter('all');
                resblock_id = '';
                resblockPoint = {
                    lng: '',
                    lat: ''
                };
                if (tqFlag) {
                    map.clearOverlays();
                    J_centerTqMarker.show();
                    backCenterFlag = true;
                    tqDragFlag = true;
                    map.centerAndZoom(new BMap.Point(RZCONFIG.lng, RZCONFIG.lat), 12);
                } else {

                    map.centerAndZoom(new BMap.Point(RZCONFIG.lng, RZCONFIG.lat), 12);
                    //_this.mapAjax();
                }


            } else if ($(this).attr('id') == 'J_clear') {
                clearFilter('allFilter');
                _this.mapAjax();
            } else {
                _this.mapAjax();
            }

        });





    }
};

rzroomMap.init();





// 复杂的自定义覆盖物
function ComplexCustomOverlay(point, text, index, type, code,cityId,countyId,townId) {
    this._point = point;
    this._text = text;
    this._index = index;
    this._type = type;
    this._code = code;
    this._cityId=cityId;
    this._countyId=countyId;
    this._townId=townId;


}
ComplexCustomOverlay.prototype = new BMap.Overlay();
ComplexCustomOverlay.prototype.initialize = function (map) {

    this._map = map;
    var that = this;

    console.log("data-code="+that._code);
    var div = this._div = document.createElement("div");
    div.style.zIndex = BMap.Overlay.getZIndex(this._index);
    div.setAttribute('data-point', this._point.lng + ',' + this._point.lat);
    div.setAttribute('data-id', this._index);
    map.getPanes().labelPane.appendChild(div);
    div.setAttribute('data-code', that._code);
    div.setAttribute('data-countyId', that._countyId);
    div.setAttribute('data-cityId', that._cityId);
    div.setAttribute('data-townId', that._townId);



    if (this._type == 'areaMarkers') { //区域大圆

        div.setAttribute('class', 'areaMarkers');
        div.innerHTML = '<p class="t">' + that._text.split("|")[0] + '</p><p class="n">' + that._text.split("|")[1] + '</p>';

        div.onmouseenter = function () {
            divIndex = this.getAttribute('data-id');
            console.log("data-id"+divIndex);
            if (this.getAttribute('data-code') != '23008629') {
                plyObj['n_' + divIndex + '_0'].show();
                if (plyObj['n_' + divIndex + '_1']) {
                    plyObj['n_' + divIndex + '_1'].show();
                }
            }



        }
        div.onmouseleave = function () {
            divIndex = this.getAttribute('data-id');
            if (this.getAttribute('data-code') != '23008629') {
                plyObj['n_' + divIndex + '_0'].hide();
                if (plyObj['n_' + divIndex + '_1']) {
                    plyObj['n_' + divIndex + '_1'].hide();
                }
            }
        }
        div.onclick = function () {
            $('#cityId').val(that._cityId);
            $('#countyId').val(that._countyId);
            $('#townId').val(that._townId);
            scrollIngFlag = false;
            district_code = that._code;
            bizcircle_code = '';
            resblock_id = '';
            resblockPoint = {
                lng: '',
                lat: ''
            };
            roomListType = 'areaMarkers';
            map.centerAndZoom(new BMap.Point(that._point.lng, that._point.lat), 15);
            ajaxFlag = false;

            clearTimeout(timer)
            timer = setTimeout(function () {
                ajaxFlag = true;
            }, 300);


            //
        }
    }
    if (this._type == 'businessMarkers') { //商圈大圆
        div.setAttribute('class', 'businessMarkers');
        div.innerHTML = '<p class="t">' + that._text.split("|")[0] + '</p><p class="n">' + that._text.split("|")[1] + '</p>';

        div.onclick = function () {
            $('#cityId').val(that._cityId);
            $('#countyId').val(that._countyId);
            $('#townId').val(that._townId);
            scrollIngFlag = false;
            district_code = ''
            bizcircle_code = that._code;

            roomListType = 'businessMarkers';
            map.centerAndZoom(new BMap.Point(that._point.lng, that._point.lat), 17);
            ajaxFlag = false;
            clearTimeout(timer)
            timer = setTimeout(function () {
                ajaxFlag = true;
            }, 300);
        }
    }
    if (this._type == 'keywordMakers') { //关键字定位
        div.setAttribute('class', 'keywordMakers');
        div.setAttribute('id', 'J_KeywordMakers');
        div.style.zIndex = '99';
        if (that._text.indexOf('|') < 0) {
            div.innerHTML = '<p>' + that._text + '</p>';
        } else {
            div.innerHTML = '<p>' + that._text.split('|')[0] + '<span id="J_tqCloseMarker" data-point="' + that._point.lng + ',' + that._point.lat + '">' + that._text.split('|')[1] + '</span></p>';
        }
    }
    if (this._type == 'keywordMakersSmall') { //关键字定位
        div.setAttribute('class', 'keywordMakersSmall');
        div.setAttribute('id', 'J_KeywordMakers');
        div.style.zIndex = '99';
    }

    if (this._type == 'keywordMakersRed') { //关键字定位
        div.setAttribute('class', 'keywordMakersRed');
        div.style.zIndex = '101';
    }

    //roundMarkers 周边marker
    if (this._type == 'roundMarkers') { //周边marker
        div.setAttribute('class', 'roundMarkers');
        div.setAttribute('title', this._text);
    }

    //houseMarkers 小区marker
    if (this._type == 'houseMarkers') { //周边marker
        div.setAttribute('class', 'houseMarkers');
        div.setAttribute('onclick', 'houseMarkersClick(this)');
        div.innerHTML = '<p>' + that._text.split('|')[0] + '</p><span class="ani2">' + that._text.split('|')[1] + '</span><b></b>';
    }


    return div;
}
ComplexCustomOverlay.prototype.draw = function () {
    var map = this._map;
    var pixel = map.pointToOverlayPixel(this._point);
    this._div.style.left = pixel.x - 15 + "px";
    this._div.style.top = pixel.y - 40 + "px";

}

//画线路
function houseMarkersClick(obj) {
    //$(obj).addClass('houseMarkersGray');
    var keywordPoint = centerPoint.split(',');
    var housePoint = $(obj).attr('data-point').split(',');
    var code = $(obj).attr('data-code');

    if (tqFlag) {
        resblockPoint = {
            lng: housePoint[0],
            lat: housePoint[1]
        };
    }

    $('.houseMarkers').removeClass('houseMarkersActive');
    $(obj).addClass('houseMarkersActive');


    transtPos.start = new BMap.Point(housePoint[0], housePoint[1]);
    transtPos.end = new BMap.Point(keywordPoint[0], keywordPoint[1]);
    if (housePoint.length > 0 && keywordPoint.length > 0 && tqFlag == true) {
        checkLine(transtPos.start, transtPos.end);
    }
    scrollIngFlag = false;
    district_code = '';
    bizcircle_code = '';
    roomListType = 'houseMarkers';
    resblock_id = code;
    rzroomMap.roomAjax();


}

//判断是何种交通方式，在拖动地图时是否要重绘线路
function checkLine(start, end) {
    //公交
    $('[stroke="#4EB1FF"]').remove();
    if (transport == 'transit') {
        transit.setPageCapacity(1);
        transit.search(start, end);
        transit.setMarkersSetCallback(function (result) {
            result[0].marker.setIcon(myLineIcon);
            result[1].marker.setIcon(myLineIcon);
            clearLineIcon();
        });


    }
    //步行+骑行
    if (transport == 'walk' || transport == 'ride') {
        walking.search(start, end);
        walking.setMarkersSetCallback(function (result) {
            result[0].marker.setIcon(myLineIcon);
            result[1].marker.setIcon(myLineIcon);
            clearLineIcon();
        });
    }
    //开车
    if (transport == 'drive') {
        driving.search(start, end);
        driving.setMarkersSetCallback(function (result) {
            result[0].marker.setIcon(myLineIcon);
            result[1].marker.setIcon(myLineIcon);
            clearLineIcon();
        });
    }
}
//清除线路图标
function clearLineIcon() {
    $('img').each(function () {
        if ($(this).attr('src') == 'http://api0.map.bdimg.com/images/trans_icons.png') {
            $(this).remove();
        }
    });
}

/*************************************地图计算线路距离*********************************************/
function fD(a, b, c) {
    for (; a > c;)
        a -= c - b;
    for (; a < b;)
        a += c - b;
    return a;
};

function jD(a, b, c) {
    b != null && (a = Math.max(a, b));
    c != null && (a = Math.min(a, c));
    return a;
};

function yk(a) {
    return Math.PI * a / 180
};

function Ce(a, b, c, d) {
    var dO = 6370996.81;
    return dO * Math.acos(Math.sin(c) * Math.sin(d) + Math.cos(c) * Math.cos(d) * Math.cos(b - a));
};

function getDistance(a, b) {
    if (!a || !b)
        return 0;
    a.lng = fD(a.lng, -180, 180);
    a.lat = jD(a.lat, -74, 74);
    b.lng = fD(b.lng, -180, 180);
    b.lat = jD(b.lat, -74, 74);
    return Ce(yk(a.lng), yk(b.lng), yk(a.lat), yk(b.lat));
};
/*************************************地图计算线路距离*********************************************/
function setUlShow() {
    var uiEl = document.getElementsByClassName('ui')[0];
    uiEl.style.display = 'block';
}

function canelUlShow() {
    var uiEl = document.getElementsByClassName('ui')[0];
    uiEl.style.display = 'none';
}
    function redirctToPage(){
        var uri=window.location.search;
        var login=$('#login');
        var register=$('#register');
        login.attr("href","/login/index?uri=/map"+encodeURIComponent(uri));
        register.attr("href","/register/index?uri=/map"+encodeURIComponent(uri))
    }
$(function(){
    redirctToPage();
})
